package com.econ.powercloud.ems.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * JoinPoint工具类
 *
 * @author chenxiaoqi
 * @since 2021/10/19
 **/
public class JoinPointUtils {

    private JoinPointUtils() {
    }

    /**
     * 获取JoinPoint方法上的注解
     *
     * @param point
     * @param annotationClass
     * @param <T>
     * @return
     */
    public static <T extends Annotation> T getMethodAnnotation(JoinPoint point, Class<T> annotationClass) {
        return getMethod(point).getAnnotation(annotationClass);
    }

    public static <T extends Annotation> T getClassAnnotation(JoinPoint point, Class<T> annotationClass) {
        return point.getTarget().getClass().getAnnotation(annotationClass);
    }

    public static Method getMethod(JoinPoint point) {
        return ((MethodSignature) point.getSignature()).getMethod();
    }

    public static Map<String, Object> getParameterMap(JoinPoint point) {
        Map<String, Object> result = new HashMap<>();
        String[] names = getParameterNames(point);
        Object[] values = getParameterValues(point);

        for (int i = 0; i < values.length; i++) {
            result.put(names[i], values[i]);
        }
        return result;
    }

    private static String[] getParameterNames(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        return signature.getParameterNames();
    }

    private static Object[] getParameterValues(JoinPoint point) {
        return point.getArgs();
    }
}
